﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Data.OracleClient;
using System.Text;
using Aspose.Excel;

public partial class Entry : BasePage
{
	public const int week1 = 8;
	public const int week2 = 16;

	protected override void pageLoad()
	{
		//SecurityCheck();
		if (!IsPostBack)
		{
			checkSection();
			FillGrid();
			go();
		}	

	
	}

	protected void checkSection()
	{
		if (SectionId < 0)
			return;

		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetSectionsShort(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, CurrentInfo.SemesterId, out message).Tables[0];
	
		PALogManager.MessageLog(message);

		bool find = false;

		foreach (DataRow dr in data.Rows)
		{
			if ((decimal)dr["SECTION_ID"] == SectionId)
			{
				find = true;
				break;
			}
		}

		if (!find)
		{
			Response.Redirect("error.aspx");
		}
	}

	protected DateTime Date
	{
		get
		{
			if(String.IsNullOrEmpty (Request.QueryString["date"]))
				return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

			return DateTime.Parse(Request.QueryString["date"]);
		}
	}
  
	DataTable _enrolledstudents = null;
	DataTable enrolledstudents
	{
		get
		{
			if (_enrolledstudents == null)
			{
				DataLayer dal = new DataLayer();

				string message = string.Empty;
				_enrolledstudents = dal.GetEnrolledStudents(PAConfiguration.ConnectionString, int.Parse(ddlSections.SelectedValue), out message);
				PALogManager.MessageLog(message);
			}

			return _enrolledstudents;
		}
	}

	protected void FillGrid()
	{		
    DataLayer dal = new DataLayer();

		string message = string.Empty;
		DataTable data = dal.GetSectionsShort(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, CurrentInfo.SemesterId, out message).Tables[0];
		PALogManager.MessageLog(message);

		CheckSections(data);
		data.DefaultView.Sort = "SECTION_TITLE";
		this.ddlSections.DataSource = data;

		
		PALogManager.MessageLog(message);
	

		this.ddlSections.DataBind();
		DateTime current;
		if (Teacher.IS_ADMIN == 1)
		{
			this.ddlPeriods.DataSource = Manager.GetTwoWeeksForAdmin(Date, CurrentInfo.FIRSTDAY, CurrentInfo.LASTDAY, out current);
		}
		else
		{
			this.ddlPeriods.Enabled = false;
			this.ddlPeriods.DataSource = Manager.GetTwoWeeks(Date, CurrentInfo.FIRSTDAY, CurrentInfo.LASTDAY, out current);
		}

        this.ddlPeriods.DataBind();
		try
		{
			if (current != DateTime.MinValue)
				this.ddlPeriods.SelectedValue = current.ToString();
		}
		catch (System.Exception ex)
		{
			PALogManager.ExceptionLog(ex);
		}
	 


	//	ddlPeriods.Enabled = (Teacher.IS_ADMIN == 1);


		try
		{
			if (SectionId > 0)
			{
				this.ddlSections.SelectedValue = SectionId.ToString();
			}
		}
		catch (System.Exception ex)
		{
			PALogManager.ExceptionLog(ex);
		}
	}

	public override string Icon
	{
		get
		{
			return "images/attendance_entry_icon.png";
		}
	}
  protected void setCodes()
  {
    DataLayer dal = new DataLayer();
    string message = string.Empty;
    DataTable codes = dal.GetCodes(PAConfiguration.ConnectionString, CurrentInfo.TermId, out message);
    PALogManager.MessageLog(message);
    bool firstChecked = false;
    int i = 0;
    bool flagAdmin = (Teacher.IS_ADMIN == 1);

    foreach (DataRow dr in codes.Rows)
    {
      //if (PAConfiguration.IsSuperUser(Teacher.TEACHER_ID) || dr["ATT_CODE"].ToString() != "O")
      {
        ++i;
        HtmlTableRow tr = CodesRow;
        if (i > 5)
          tr = CodesRow1;

        HtmlTableCell cell = new HtmlTableCell();
        HtmlInputRadioButton checkbox = new HtmlInputRadioButton();
        
        checkbox.Value = Convert.ToString(dr["ATTENDANCE_CODE_ID"]);
        cell.Controls.Add(checkbox);

        if ((!flagAdmin) && ((dr["ATT_CODE"].ToString() == "E") || (dr["ATT_CODE"].ToString() == "W") ||
          (dr["ATT_CODE"].ToString() == "Q") || (dr["ATT_CODE"].ToString() == "S") || (dr["ATT_CODE"].ToString() == "O")))
        {
            //cell.Controls.Remove(checkbox);
            checkbox.Attributes.Add("disabled", "disabled");
        }
        else
        {
            if (!firstChecked)
            {
                checkbox.Checked = true;
                firstChecked = true;
            }
        }

        Label l = new Label();
        l.Font.Size = 9;
        l.Text = String.Format("{0}-{1}", dr["ATT_CODE"], dr["DESCRIPTION"]);

        cell.Controls.Add(l);
        tr.Cells.Add(cell);
      }
    }

    if (flagAdmin)
      ClientScript.RegisterStartupScript(this.GetType(), "isadmin", "var isadmin=1;", true);
    else
      ClientScript.RegisterStartupScript(this.GetType(), "isadmin", "var isadmin=0;", true);
  }

	protected void go()
	{
		if (ddlSections.SelectedValue == string.Empty)
			return;

		if (ddlPeriods.SelectedValue == string.Empty)
			return;


		AttendanceEntry entry = Manager.GetEntry(
			decimal.Parse(ddlSections.SelectedValue),
			DateTime.Parse(ddlPeriods.SelectedValue),
			DateTime.Parse(ddlPeriods.SelectedValue).AddDays(13));

		Records = entry.Records;

		gvEntries.Columns.Clear();


		//BoundField field = new BoundField(); //ZH 9/12/2011
        HyperLinkField field = new HyperLinkField();
        field.NavigateUrl = "StudentEntry.aspx";
        field.DataNavigateUrlFields = new String[] { "student_id" };
        field.DataNavigateUrlFormatString = "StudentEntry.aspx?studentId={0}";
		field.ItemStyle.Width = 200;
        //field.DataField = "LastFirst"; //ZH 9/12/2011
        field.DataTextField = "LastFirst";
		field.HeaderText = "Student Name";
		field.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
		field.ItemStyle.Font.Size = 10;
		gvEntries.Columns.Add(field);
		for (int i = 3; i < 19; i++)
		{
			if (i - 2 == week1)
			{

				TemplateField cf = new TemplateField();
				cf.ItemTemplate = new DynamicButtonTemplate(string.Empty, DataControlRowType.DataRow);
				cf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
				gvEntries.Columns.Add(cf);
				
				cf.ItemStyle.Width = 40;

				continue;
			}

			if (i - 2 == week2)
			{

				TemplateField cf = new TemplateField();
				cf.ItemTemplate = new DynamicButtonTemplate(string.Empty, DataControlRowType.DataRow);
				cf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
				gvEntries.Columns.Add(cf);
				
				cf.ItemStyle.Width = 40;
				continue;
			}

			TemplateField celltemplate = new TemplateField();
			celltemplate.HeaderText = entry.Result.Columns[i].ColumnName;
			celltemplate.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
			celltemplate.ItemTemplate = new DynamicSellTemplate();
			gvEntries.Columns.Add(celltemplate);
		}


		TemplateField lastcell = new TemplateField();
		lastcell.ItemTemplate = new DynamicLastTemplate();
		gvEntries.Columns.Add( lastcell);
		

		setCodes();

		PlaceHolder1.Controls.Add(ParseControl(getHeader(gvEntries.Columns)));

		gvEntries.DataSource = entry.Result;
		gvEntries.DataBind();


	}
  
  protected void gvEntries_RowDataBound(object sender, GridViewRowEventArgs e)
	{

		if (e.Row.RowType != DataControlRowType.DataRow)
			return;

		DataRow row = ((DataRowView)e.Row.DataItem).Row;

		decimal studentId = (decimal)row["STUDENT_ID"];
		decimal enrollmentId = (decimal)row["ENROLLMENT_ID"];

		HtmlInputHidden hiddenField = new HtmlInputHidden();
		hiddenField.Value = string.Format("{0}, {1}", enrollmentId, DateTime.Parse(ddlPeriods.SelectedValue));
		e.Row.Cells[week1].Controls.Add(hiddenField);
		hiddenField = new HtmlInputHidden();
		hiddenField.Value = string.Format("{0}, {1}", enrollmentId, DateTime.Parse(ddlPeriods.SelectedValue).AddDays(7));
		e.Row.Cells[week2].Controls.Add(hiddenField);

		DateTime start = DateTime.Parse(ddlPeriods.SelectedValue);

		bool AllN = true;
		for (int i = 1; i < 8; i++)
		{
			TableCell tc = e.Row.Cells[i];
			DataRow erow = Manager.Find(Records, studentId, enrollmentId, start);
			

			hiddenField = new HtmlInputHidden();
		hiddenField.Value = string.Format("{0}, {1}", enrollmentId, start);
		tc.Controls.Add(hiddenField);
        start = start.AddDays(1);
			Label l = (Label)tc.Controls[0];
			HtmlInputText tb = (HtmlInputText)tc.Controls[1];
			
			if (erow != null)
			{


				l.Text = (string)erow["ATT_CODE"];
				tb.Value = (string)erow["ATT_CODE"];


				if (erow.IsNull("OTHER_CODES"))
					tb.Attributes["other_codes"] = string.Empty;
				else
				{
					tb.Attributes["other_codes"] = (string)erow["OTHER_CODES"];

					l.ToolTip = string.Format("Other Codes: {0}",(string)erow["OTHER_CODES"]);
				}

				if (tb.Value != "N")
					AllN = false;

				

				if (!erow.IsNull("OTHER_CODES"))
				{
					tc.BackColor = Color.LightBlue;
				}
			}
			else
			{
				AllN = false;
			}
			
			tc.Controls.Add(l);
			
		}

		if (AllN)
		{
			e.Row.Cells[0].Attributes["class"] = "bold";
			e.Row.Cells[0].Font.Bold = true;
			for (int i = 1; i < 8; i++)
			{
				TableCell tc = e.Row.Cells[i];
				e.Row.Cells[i].BackColor = Color.Yellow;
			}
		}

		AllN = true;
		for (int i = 9; i < 16; i++)
		{
			TableCell tc = e.Row.Cells[i];

			DataRow erow = Manager.Find(Records, studentId, enrollmentId, start);
			hiddenField = new HtmlInputHidden();
			hiddenField.Value = string.Format("{0}, {1}", enrollmentId, start);
			tc.Controls.Add(hiddenField);

			start = start.AddDays(1);
			Label l = (Label)tc.Controls[0];
			HtmlInputText tb = (HtmlInputText)tc.Controls[1];
			if (erow != null)
			{


				l.Text = (string)erow["ATT_CODE"];
				tb.Value = (string)erow["ATT_CODE"];

				if (erow.IsNull("OTHER_CODES"))
					tb.Attributes["other_codes"] = string.Empty;
				else
				{
					tb.Attributes["other_codes"] = (string)erow["OTHER_CODES"];

					l.ToolTip = string.Format("Other Codes:{0}", (string)erow["OTHER_CODES"]);
				}

				if (tb.Value != "N")
					AllN = false;


				if (!erow.IsNull("OTHER_CODES"))
				{
					tc.BackColor = Color.LightBlue;
				}
			}
			else
			{
				AllN = false;
			}
			tc.Controls.Add(l);
		}

		TableCell cell =  e.Row.Cells[17];
		HyperLink hl = (HyperLink)cell.Controls[0];

		hl.ImageUrl = "~/images/icons/log_entries.png";
		hl.NavigateUrl = string.Format("logentries.aspx?sectionId={0}&studentId={1}", decimal.Parse(ddlSections.SelectedValue), studentId);
		hl.Text = "Test";

		cell = e.Row.Cells[0];
		HyperLink hls = (HyperLink) cell.Controls[0];


		foreach (DataRow dr in enrolledstudents.Rows)
		{
			if ((decimal)dr["STUDENT_ID"] == studentId)
			{
				DateTime dt = (DateTime)dr["DATE_ENROLLED"];

				DateTime startе = DateTime.Parse(ddlPeriods.SelectedValue);
				DateTime endе =  DateTime.Parse(ddlPeriods.SelectedValue).AddDays(13);

				if((dt.Ticks >= startе.Ticks) && (dt.Ticks <= endе.Ticks))
					hls.Text += string.Format(" ({0}/{1})", dt.Month, dt.Day);
			}
		}
		//hls.Text += " (12/2)";
		//DataLayer dal = new DataLayer();
		
		//Student student = dal.(PAConfiguration.ConnectionString, studentId, out message);

		//if(student.
		if (AllN)
		{
			e.Row.Cells[0].Attributes["class"] = "bold";
			e.Row.Cells[0].Font.Bold = true;
			for (int i = 9; i < 16; i++)
			{
				TableCell tc = e.Row.Cells[i];

				
				e.Row.Cells[i].BackColor = Color.Yellow;
			}
		}
		
	}
  
	protected DataTable Records
	{
		get
		{
			return (DataTable)Session["Records"];
		}
		set
		{
			Session["Records"] = value;
		}
	}
	protected void lbExport_Click(object sender, EventArgs e)
	{
    DataTable toExcel = Manager.GetForExcel(
      decimal.Parse(ddlSections.SelectedValue),
      DateTime.Parse(ddlPeriods.SelectedValue),
      DateTime.Parse(ddlPeriods.SelectedValue).AddDays(13));

    Manager.ExportToCSV(toExcel, this.Context, "entry_report.csv");
	}
	protected void bGo_Click(object sender, ImageClickEventArgs e)
	{
		go();
	}
}
